const express = require('express');
const path = require('path');
const morgan = require('./modules/logger')
const dotenv = require('dotenv')
const sendResult = require('./modules/sendResult')
const database = require('./modules/databse')
const cors = require('./modules/cors')
const bodyParser = require('body-parser')
const passport = require('./modules/passport')
const managerService = require('./services/ManagerService')
const roleService = require('./services/RoleService')
const getAllRouterFileExport = require('./modules/getAllRouterFileExport')
const imagesUploader = require('./modules/uploads/images')
const ueditorUploader = require('./modules/uploads/ueditor')


// 加载环境变量
dotenv.config()

const app = express();

// 初始化数据库模块
database.InitOrmModel(app, function (err) {
  if (err) {
    console.error('连接数据库失败失败:', err)
  }
})

// 跨域设置
cors(app)

app.use(morgan);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// 统一响应返回结构
app.use(sendResult)


// 登录函数衔接passport策略
passport.setup(app, managerService.login)

// 设置 passport 登录入口点
app.use('/api/private/v1/login', passport.login)
// 设置 passport 验证路径
app.use('/api/private/v1/*', passport.tokenAuth)
// 动态遍历目录加载所有路由
getAllRouterFileExport(path.join(__dirname, '/routes/api/private/v1'),  async(router, fileName) => {
  await app.use(`/api/private/v1/${path.parse(fileName).name}`, router)
})


// 验证模块
const authorization = require(path.join(process.cwd(), '/modules/authorization'))
// 设置全局权限
authorization.setAuthFn(function (req, res, next, serviceName, actionName, passFn) {
  if (!req.userInfo || isNaN(parseInt(req.userInfo.rid))) return res.sendResult('无角色ID分配')
   // 验证权限
   roleService.authRight(req.userInfo.rid, serviceName, actionName, function(err, pass) {
    passFn(pass)
  })
})

// 图片上传

app.use('/api/private/v1/uploads/images', imagesUploader)

// 富文本上传
app.use('/api/private/v1/uploads/ueditor', ueditorUploader)
// 开启图片的静态资源服务器
app.use('/public/images', express.static('./public/images'))
app.use('/public/ueditor', express.static('./public/ueditor'))

// 设置apidoc接口文档静态文件目录
app.use(express.static(path.join(__dirname, 'public')));

app.use(function(req, res, next) {
  res.sendResult(null, 404, 'Not Found')
});



module.exports = app;
